package com.abing.chatRoom.controller;

import com.abing.chatRoom.common.ErrorCode;
import com.abing.chatRoom.common.ResultUtils;
import com.abing.chatRoom.exception.BusinessException;
import com.abing.chatRoom.model.VO.UserVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.abing.chatRoom.common.BaseResponse;
import com.abing.chatRoom.model.domain.User;
import com.abing.chatRoom.model.request.ForgetPasswordRequest;
import com.abing.chatRoom.model.request.UserLoginRequest;
import com.abing.chatRoom.model.request.UserRegisterRequest;
import com.abing.chatRoom.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.abing.chatRoom.contant.UserConstant.USER_LOGIN_STATE;

/**
 * 用户接口
 *
 @author <a href="https://gitee.com/iooioioiooi">abing</a>
 */
@RestController
@RequestMapping("/user")
@CrossOrigin(originPatterns = {"http://localhost"}, allowCredentials = "true", allowedHeaders = {"*"})
@Slf4j
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 用户注册
     *
     * @param userRegisterRequest
     * @return
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        // 校验
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String phone= userRegisterRequest.getPhone();
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword, phone)) {
            return null;
        }
        Long result = userService.userRegister(userAccount, userPassword, checkPassword, phone);
        return ResultUtils.success(result);
    }

    /**
     * 用户登录
     *
     * @param userLoginRequest
     * @param request
     * @return
     */
    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(user);
    }

    /**
     * 用户注销
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        int result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

    /**
     * 获取当前用户
     *
     * @param request
     * @return
     */
    @GetMapping("/current")
    public BaseResponse<User> getCurrentUser(HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        long userId = currentUser.getId();
        // TODO 校验用户是否合法
        User user = userService.getById(userId);
        User safetyUser = userService.getSafetyUser(user);
        return ResultUtils.success(safetyUser);
    }

    // https://yupi.icu/

    @GetMapping("/search")
    public BaseResponse<List<User>> searchUsers(String username, HttpServletRequest request) {
        if(request==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(username)) {
            queryWrapper.like("username", username);
        }
        List<User> userList = userService.list(queryWrapper);
        List<User> list = userList.stream().map(user -> userService.getSafetyUser(user)).collect(Collectors.toList());
        return ResultUtils.success(list);
    }

    @GetMapping("/delete")
    public BaseResponse<Boolean> deleteUser( long id, HttpServletRequest request) {
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean save = userService.removeById(id);
        return ResultUtils.success(save);
    }


    @GetMapping("/search/tags")
    public BaseResponse<List<User>>searchUserByTags(@RequestParam(required = false) List<String>tagNameList){

        if(CollectionUtils.isEmpty(tagNameList)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        List<User> users = userService.searchUserByTags(tagNameList);
        return ResultUtils.success(users);

    }


    @PostMapping("/update")
    public BaseResponse<Integer>updataUser(@RequestBody User user,HttpServletRequest request){
        //判断参数是否为空
        if(user==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //获取用户,鉴权
        User loginUser = userService.getLoginUser(request);
        int result= userService.updateUser(user, loginUser);
        return ResultUtils.success(result);
    }
    /**
     * 推荐页面
     * @param request
     * @return
     */
    @GetMapping("/recommend")
    public BaseResponse<Page<User>> recommendUsers(long pageSize,long pageNum, HttpServletRequest request){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();

        String redisKey = null;
        ValueOperations<String,Object> valueOperations = null;
        Page<User> userPage= null;
        try {
            User loginUser = userService.getLoginUser(request);
            redisKey = String.format("partner:user:recommend:%s", loginUser.getId());
            valueOperations = redisTemplate.opsForValue();
            //如果有缓存，直接读缓存
            userPage = (Page<User>)valueOperations.get(redisKey);
            if (userPage!=null){
                return ResultUtils.success(userPage);
            }
        } catch (Exception e) {}
        //无缓存，查数据库
        userPage = userService.page(new Page<>(pageNum, pageSize), queryWrapper);
        //写缓存
        try {
            valueOperations.set(redisKey,userPage,30000, TimeUnit.MILLISECONDS);
        }catch (Exception e){
            log.error("redis set key error",e);
        }
        return ResultUtils.success(userPage);
    }

    /**
     * 心动匹配
     * @param num
     * @param request
     * @return
     */
    @GetMapping("/match")
    public BaseResponse<List<User>>matchUsers( long num,HttpServletRequest request){
        if(num<=0||num>20){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        List<User> userList = userService.matchUsers(num, loginUser);
        return ResultUtils.success(userList);
    }

    @PostMapping("/forget")
    public BaseResponse<Boolean>forgetPassword(@RequestBody ForgetPasswordRequest forgetPasswordRequest, HttpServletRequest request){
        if(request==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String phone = forgetPasswordRequest.getPhone();
        String userPassword = forgetPasswordRequest.getUserPassword();
        String checkPassword = forgetPasswordRequest.getCheckPassword();
        if(StringUtils.isAnyBlank(phone,userPassword,checkPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        userService.updatePassword(phone,userPassword,checkPassword);

        return ResultUtils.success(true);
    }

    @GetMapping("/getUserById")
    public BaseResponse<UserVO> getUserById(Long id, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        if(loginUser==null){
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        if(id==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getById(id);
        if(user==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user,userVO);
        return ResultUtils.success(userVO);
    }
    @GetMapping("/{id}")
    public BaseResponse<UserVO> getUserById(@PathVariable long id,HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        if(loginUser==null){
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        User user = userService.getById(id);
        if(user==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user,userVO);
        return ResultUtils.success(userVO);
    }

}
